﻿<%@ WebHandler Language="C#" Class="MfgorderFinishRateDashBoard" %>

using System;
using System.IO;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using System.Collections.Generic;
using System.Data;
using System.Text;
using ReportBusiness;
using System.Net;

/**
 * Description: 订单完成率看板（生产部）
 * Copyright (c): 通力凯顿（北京）系统集成有限公司
 * Author: zhunan
 * Date: 2022.6.16
 */

public class MfgorderFinishRateDashBoard : IHttpHandler
{
    uMESReportOracleDAL dal = new uMESReportOracleDAL();
    public bool IsReusable { get { return false; } }
    public void ProcessRequest(HttpContext context)
    {
        string requestjson = "";
        using (StreamReader reader = new StreamReader(context.Request.InputStream)) { requestjson = reader.ReadToEnd(); }
        JObject jObject = JsonConvert.DeserializeObject(requestjson) as JObject;
        if (jObject["type"] != null)
        {
            try
            {
                Result r = new Result();
                context.Response.ContentType = "text/json";
                string type = jObject["type"].ToString();
                switch (type)
                {
                    case "getData":
                        r = getData(jObject);//订单完成率（折线图）
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getDetail":
                        r = getDetail(jObject);//明细
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getExportExcel":
                        getExportExcel(jObject);//导出
                        break;
                    default:
                        break;
                }
            }
            catch (Exception e)
            {
                Result r = new Result();
                r.data = null;
                r.meta = new Result.Meta(500, e.Message);
                r.total = 0;
                context.Response.ContentType = "text/json";
                context.Response.Write(JsonConvert.SerializeObject(r));
            }
        }
    }

    Result getData(JObject jObject)
    {
        string sql = @"
SELECT t1.factoryname,COUNT(1) total,
       SUM(CASE WHEN t1.status='未开卡' THEN 1 ELSE 0 END) notstart,
       SUM(CASE WHEN t1.status='未完成' THEN 1 ELSE 0 END) notfinished,
       SUM(CASE WHEN t1.status = '超期完成' THEN 1 WHEN t1.status='按时完成' THEN 1 ELSE 0 END) finished,
       SUM(CASE WHEN t1.status='按时完成' THEN 1 ELSE 0 END) intimefinished,
       SUM(CASE WHEN t1.status='超期完成' THEN 1 ELSE 0 END) dualfinished,
       round(SUM(CASE WHEN t1.status = '超期完成' THEN 1 WHEN t1.status='按时完成' THEN 1 ELSE 0 END) / COUNT(1),4) * 100 finishrate,
       ROUND(SUM(CASE WHEN t1.status='按时完成' THEN 1 ELSE 0 END) / COUNT(1),4) * 100 intimefinishrate
FROM
(
    SELECT t.factoryname,t.mfgordername,
           CASE WHEN COUNT(1) = SUM(t.isinstore) AND TRUNC(MAX(t.createdate)) - TRUNC(t.plannedcompletiondate) > 0 THEN '超期完成'
                WHEN COUNT(1) = SUM(t.isinstore) AND TRUNC(MAX(t.createdate)) - TRUNC(t.plannedcompletiondate) <= 0 THEN '按时完成'
                WHEN COUNT(1) <> SUM(t.isinstore) THEN '未完成' 
           END status
    FROM 
    (
      SELECT f.factoryname,cci.mfgordername,mfg.plannedcompletiondate,cci.containername,cid.createdate,
             CASE WHEN cid.aufnr IS NOT NULL THEN 1 ELSE 0 END isinstore
      FROM containercurrentinfo cci
      LEFT JOIN mes_factory_mapping f ON f.factoryid = cci.originalfactoryid
      LEFT JOIN containerinstore cid ON cid.aufnr = cci.mfgordername AND cid.charg = cci.containername AND cid.createdate IS NOT NULL
      LEFT JOIN mfgorder mfg ON mfg.mfgorderid = cci.mfgorderid
      WHERE cci.workflowroute IS NULL AND cci.containerstatus <> 2 
            AND f.factorycode IN ('600','601','607','608','609') ";

        if (jObject["selectdate"] != null && jObject["selectdate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["selectdate"].ToString());
            if (arr.Count >= 2)
            {
                sql += string.Format(" AND mfg.plannedcompletiondate >= to_date('{0} 00:00:00','yyyy-MM-dd hh24:mi:ss') ", arr[0].ToString());
                sql += string.Format(" AND mfg.plannedcompletiondate <= to_date('{0} 23:59:59','yyyy-MM-dd hh24:mi:ss') ", arr[1].ToString());
            }
        }

        sql += @"
    ) t
    GROUP BY t.factoryname,t.mfgordername,t.plannedcompletiondate

    UNION ALL

    SELECT f.factoryname,mfg.mfgordername,'未开卡' status
    FROM mfgorder mfg
    LEFT JOIN mes_factory_mapping f ON f.factoryid = mfg.factoryid
    LEFT JOIN containercurrentinfo cci ON cci.mfgorderid = mfg.mfgorderid
    WHERE f.factorycode IN ('600','601','607','608','609') AND cci.containerid IS NULL ";

        if (jObject["selectdate"] != null && jObject["selectdate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["selectdate"].ToString());
            if (arr.Count >= 2)
            {
                sql += string.Format(" AND mfg.plannedcompletiondate >= to_date('{0} 00:00:00','yyyy-MM-dd hh24:mi:ss') ", arr[0].ToString());
                sql += string.Format(" AND mfg.plannedcompletiondate <= to_date('{0} 23:59:59','yyyy-MM-dd hh24:mi:ss') ", arr[1].ToString());
            }
        }

        sql += @"
) t1
GROUP BY t1.factoryname";
        DataTable dt = dal.GetDataTable(sql);
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dt;
        r.total = Convert.ToInt32(dt.Rows.Count);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    string getDetailSql(JObject jObject)
    {
        string sql = @"
SELECT t.factoryname,t.mfgordername,t.plannedcompletiondate,
       CASE WHEN t.status = '未完成' THEN NULL ELSE t.createdate END createdate,
       t.status
FROM 
(
  SELECT t.factoryname,t.mfgordername,t.plannedcompletiondate,MAX(t.createdate) createdate,
         CASE WHEN COUNT(1) = SUM(t.isinstore) AND TRUNC(MAX(t.createdate)) - TRUNC(t.plannedcompletiondate) > 0 THEN '超期完成'
              WHEN COUNT(1) = SUM(t.isinstore) AND TRUNC(MAX(t.createdate)) - TRUNC(t.plannedcompletiondate) <= 0 THEN '按时完成'
              WHEN COUNT(1) <> SUM(t.isinstore) THEN '未完成' 
         END status
  FROM 
  (
    SELECT f.factoryname,cci.mfgordername,mfg.plannedcompletiondate,cci.containername,cid.createdate,
           CASE WHEN cid.aufnr IS NOT NULL THEN 1 ELSE 0 END isinstore
    FROM containercurrentinfo cci
    LEFT JOIN factory f ON f.factoryid = cci.originalfactoryid
    LEFT JOIN containerinstore cid ON cid.aufnr = cci.mfgordername AND cid.charg = cci.containername AND cid.createdate IS NOT NULL
    LEFT JOIN mfgorder mfg ON mfg.mfgorderid = cci.mfgorderid
    WHERE cci.workflowroute IS NULL AND cci.containerstatus <> 2 ";

        sql += string.Format(" AND f.factoryname = '{0}'", jObject["factoryname"].ToString());
        if (jObject["selectdate"] != null && jObject["selectdate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["selectdate"].ToString());
            if (arr.Count >= 2)
            {
                sql += string.Format(" AND mfg.plannedcompletiondate >= to_date('{0} 00:00:00','yyyy-MM-dd hh24:mi:ss') ", arr[0].ToString());
                sql += string.Format(" AND mfg.plannedcompletiondate <= to_date('{0} 23:59:59','yyyy-MM-dd hh24:mi:ss') ", arr[1].ToString());
            }
        }

        sql += @"
  ) t
  GROUP BY t.factoryname,t.mfgordername,t.plannedcompletiondate
  UNION ALL
  SELECT f.factoryname,mfg.mfgordername,mfg.plannedcompletiondate,NULL createdate,'未开卡' status
  FROM mfgorder mfg
  LEFT JOIN factory f ON f.factoryid = mfg.factoryid
  LEFT JOIN containercurrentinfo cci ON cci.mfgorderid = mfg.mfgorderid
  WHERE cci.containerid IS NULL ";

        sql += string.Format(" AND f.factoryname = '{0}'", jObject["factoryname"].ToString());
        if (jObject["selectdate"] != null && jObject["selectdate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["selectdate"].ToString());
            if (arr.Count >= 2)
            {
                sql += string.Format(" AND mfg.plannedcompletiondate >= to_date('{0} 00:00:00','yyyy-MM-dd hh24:mi:ss') ", arr[0].ToString());
                sql += string.Format(" AND mfg.plannedcompletiondate <= to_date('{0} 23:59:59','yyyy-MM-dd hh24:mi:ss') ", arr[1].ToString());
            }
        }

        sql += @"
) t ";

        if (jObject["seriesName"].ToString() == "已完成")
        {
            sql += " WHERE t.status in ('超期完成','按时完成') ";
        }
        if (jObject["seriesName"].ToString() == "按时完成")
        {
            sql += " WHERE t.status in ('按时完成') ";
        }
        if (jObject["seriesName"].ToString() == "未完成")
        {
            sql += " WHERE t.status in ('未完成') ";
        }
        if (jObject["seriesName"].ToString() == "未开卡")
        {
            sql += " WHERE t.status in ('未开卡') ";
        }
        sql += @"
ORDER BY t.plannedcompletiondate DESC";
        return sql;
    }

    Result getDetail(JObject jObject)
    {
        string sql = getDetailSql(jObject);
        uMESPagingDataDTO dto = dal.GetPagingDataIns(sql, (int)jObject["currentPage"], (int)jObject["pageSize"]);
        DataTable dt = dto.DBTable;
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dt;
        r.total = Convert.ToInt32(dto.RowCount);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    void getExportExcel(JObject jObject)
    {
        string sql = getDetailSql(jObject);
        DataTable dt = dal.GetDataTable(sql);
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        dt.Columns["factoryname"].Caption = "主制分厂";
        dt.Columns["mfgordername"].Caption = "订单号";
        dt.Columns["plannedcompletiondate"].Caption = "计划完成时间";
        dt.Columns["createdate"].Caption = "实际完成时间";
        dt.Columns["status"].Caption = "状态";
        ExportHelper.ExportExcel(dt, jObject["title"].ToString());
    }
}